package app

import (
	"log"
	"net/http"

	"UserBalance/config"
	"UserBalance/internal/handlers"
	"UserBalance/internal/repositories"

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"
	"github.com/jackc/pgx"
)

func Run(cfg *config.Config) {

	conn, err := pgx.Connect(pgx.ConnConfig{
		Host:     cfg.DB.Host,
		Port:     cfg.DB.Port,
		Database: cfg.DB.Database,
		User:     cfg.DB.User,
		Password: cfg.DB.Password,
	})

	if err != nil {
		log.Fatalf("Нет подключения к базе: %e", err)
	}

	r := chi.NewRouter()
	r.Use(middleware.Logger)

	balanceRep := repositories.NewBalanceRepository(conn)
	balanceHandler := handlers.NewBalanceHandler(balanceRep)

	r.Get("/", balanceHandler.RootHandler)
	r.Get("/balance/user/{userID}", balanceHandler.GetBalanceHandler())
	r.Get("/transactionReport/user/{userID}", balanceHandler.GetTransactionsHandler())
	r.Get("/accountingReport/month/{month}/year/{year}", balanceHandler.GetAccountingReportHandler())

	r.Post("/balance/user/{userID}/balance/{balance}", balanceHandler.PostBalanceHandler())
	r.Post("/reserve/user/{userID}/amount/{amount}", balanceHandler.PostResevreHandleer())

	r.Put("/balance/user/{userID}/balance/{balance}", balanceHandler.PutBalanceHandler())
	r.Put("/transfer/user/{user1}/to/{user2}/sum/{sum}", balanceHandler.TransferMoneyHandler())
	r.Put("/refresh/user/{userID}/", balanceHandler.RefreshMoneyHandler())

	r.Delete("/reserve/user/{userID}/", balanceHandler.DeleteReserveHandler())

	http.ListenAndServe(":8080", r)
}
